package network;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpEchoClient {
    private DatagramSocket socket = null;
    private String serverIP;
    private int serverPort;

    //此处，ip使用的字符串，点分十进制风格：“192.168.1.23”
    public UdpEchoClient(String serverIP,int servePort) throws SocketException {
        //
        this.serverIP = serverIP;
        this.serverPort = servePort;
        socket = new DatagramSocket();
    }

    public void start() throws IOException {
        //
        System.out.println("客户端启动！");
        Scanner scanner = new Scanner(System.in);

        while(true){
            //要做四个事情
            //1.提示用户输入请求
            System.out.println("->");
            //2.从控制台读取请求
            if(!scanner.hasNext()){
                break;
            }
            String request = scanner.nextLine();

            //3.将请求构造成数据报，并发送给服务器
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length, InetAddress.getByName(serverIP),serverPort);
            socket.send(requestPacket);

            //4.读取服务器的响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);
            //String response = new String(responsePacket.getData());
            String response = new String (responsePacket.getData(),0,responsePacket.getLength());
            System.out.println(response);
        }

    }

    public static void main(String[] args) throws IOException {
        //UdpEchoClient client = new UdpEchoClient("127.0.0.1",9090);
        UdpEchoClient client = new UdpEchoClient("127.2.0.1",9090);//这里，在同一台主机上测试运行，127开头的IP地址，哪个都行~~~
        client.start();
    }
}
